package ru.st.selenium.pages;

import static org.junit.Assert.assertEquals;
import static org.openqa.selenium.support.ui.ExpectedConditions.*;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import ru.st.selenium.applogic.ApplicationManager;

public class InternalPage extends AnyPage {
private StringBuffer verificationErrors = new StringBuffer();

	public InternalPage(PageManager pages) {
		super(pages);
	}
	
  public InternalPage ensurePageLoaded() {
    super.ensurePageLoaded();
    wait.until(presenceOfElementLocated(By.cssSelector("nav")));
    return this;
  }
  
  @FindBy(css = "nav a[href $= '?go=profile']")
  private WebElement userProfileLink;

  @FindBy(css = "nav a[href $= '?go=users']")
  private WebElement userManagementLink;

  @FindBy(css = "nav a[onclick $= '?logout']")
  private WebElement logoutLink;
  
  
  @FindBy(id = "q")
  private WebElement SearchElement;
  
  
  public UserProfilePage clickUserProfilePage() {
    userProfileLink.click();
    return pages.userProfilePage;
  }

  public UserManagementPage clickUserManagementLink() {
    userManagementLink.click();
    return pages.userManagementPage;
  }
  
  public InternalPage setSearchElement(String text) {
	  SearchElement.clear();
	  SearchElement.sendKeys(text);
	  SearchElement.sendKeys(Keys.ENTER);
	  driver
	  .get(ApplicationManager.
			  baseUrl + "/#!/search/" + text + "/sort/name%20asc/");  
	    return this;
	  }  
  
  public InternalPage FindResult(String TextElement, String SearchElementText) 
  {  String elementText;
	if (SearchElementText == "div.content") {
		  elementText = driver
				  .findElement(By.cssSelector("div.content")).getText();  
	  }
	else 
		elementText = driver
		.findElement(By.cssSelector("div.title")).getText();
    try {
	        assertEquals(TextElement, elementText);
	      } catch (Error e) {
	        verificationErrors.append(e.toString());
	      }
	    return this;
	  } 
  
  
  public LoginPage clickLogoutLink() {
    logoutLink.click();
    wait.until(alertIsPresent()).accept();
    return pages.loginPage;
  }
}
